package com.pxene.dmp.main;

import java.util.Date;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.pxene.dmp.common.DateUtils;
import com.pxene.dmp.constant.FileSuffixTime;

public class JobManager {
	public static void main(String[] args) throws Exception {
		// 根据参数执行不同的job
		Options options = new Options();
		// 生产
		options.addOption("runData", false, "");
		options.addOption("runDataOn", true, "arguement is yyyyMMddHH");
		// 测试
		options.addOption("testData", false, "");
		options.addOption("testDataOn", true, "arguement is yyyyMMddHH");
		
		CommandLineParser parser = new BasicParser();
		CommandLine line = parser.parse(options, args);
		
		String jobName = null;
		boolean isTest = false;
		if (line.hasOption("runData")) {
			jobName = "runDataJob";
		} else if (line.hasOption("runDataOn")) {
			String time = line.getOptionValue("runDataOn");
			if (timeIsValid(time)) {
				jobName = "runDataJob";
				FileSuffixTime.setDate(time.substring(0, 8));
				FileSuffixTime.setHour(time.substring(8, 10));
			}
		} else if (line.hasOption("testData")) {
			isTest = true;
			jobName = "runDataJob";
		} else if (line.hasOption("testDataOn")) {
			isTest = true;
			String time = line.getOptionValue("testDataOn");
			if (timeIsValid(time)) {
				jobName = "runDataJob";
				FileSuffixTime.setDate(time.substring(0, 8));
				FileSuffixTime.setHour(time.substring(8, 10));
			}
		} else {
			HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("options", options);
		}
		
		if (jobName != null) {
			if (isTest) {
				System.setProperty("config-file", "test.properties");
			} else {
				System.setProperty("config-file", "produce.properties");
			}
			AbstractApplicationContext context = new ClassPathXmlApplicationContext("/spring/spring-core.xml");
			context.registerShutdownHook();
			JobLauncher launcher = (JobLauncher)context.getBean("jobLauncher");
			Job job = (Job)context.getBean(jobName);
			launcher.run(job, new JobParameters());
			context.close();
		}
	}
	
	// 数据的时间范围（当前时间100天前~当前时间2小时前）
	private static boolean timeIsValid(String time) {
		// 首先格式必须为yyyyMMddHH
		if(!time.matches("^[0-9]{10}$")) {
			return false;
		}
		Date date = new Date();
		String format = "yyyyMMddHH";
		String starttime = DateUtils.getFormat(DateUtils.addDays(date, -100), format);
		String endtime = DateUtils.getFormat(DateUtils.addHours(date, -2), format);
		
		return DateUtils.isBetween(time, starttime, endtime, format);
	}
	
}
